package com.itheima.controller;

import com.alibaba.dubbo.common.utils.CollectionUtils;
import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.github.pagehelper.Page;

import com.itheima.constant.MessageConstant;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.entity.Result;
import com.itheima.pojo.Order;
import com.itheima.pojo.OrderSetting;
import com.itheima.service.OrderService;
import com.itheima.service.OrderSettingService;
import com.itheima.utils.POIUtils;
import com.itheima.utils.SMSUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping(path = "/ordersetting")
public class OrderSettingController {

    @Reference
    private OrderSettingService orderSettingService;

    @Reference
    OrderService orderService;

    /**
     * 上传Excel文件
     *
     * @param excelFile
     * @return
     */
    @PostMapping(path = "/upload")
    public Result upload(MultipartFile excelFile) {
        try {
            //读取excel数据
            List<String[]> excel = POIUtils.readExcel(excelFile);
            //解析excel数据
            List<OrderSetting> orderSettings = excel.stream().map(strings -> {
                OrderSetting orderSetting = new OrderSetting();
                try {
                    orderSetting.setOrderDate(new SimpleDateFormat("yyyy/MM/dd").parse(strings[0]));
                    orderSetting.setNumber(Integer.parseInt(strings[1]));
                } catch (ParseException e) {
                    e.printStackTrace();
                    throw new RuntimeException(e.getMessage());
                }
                return orderSetting;
            }).collect(Collectors.toList());

            //只有当读取的数据不为空 , 才需要导入数据
            if (CollectionUtils.isNotEmpty(orderSettings)) {
                //将文档数据保存到数据库
                orderSettingService.add(orderSettings);
            }

            return new Result(true, MessageConstant.IMPORT_ORDERSETTING_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.IMPORT_ORDERSETTING_FAIL);
        }
    }

    /**
     * 根据月份查询预约信息
     *
     * @param date
     * @return
     */
    @GetMapping(path = "/getOrderSettingsByMonth")
    public Result getOrderSettingsByMonth(String date) {
        try {
            //根据月份查询预约信息
            List<Map<String, Object>> orderSettings = orderSettingService.getOrderSettingsByMonth(date);
            return new Result(true, MessageConstant.GET_ORDERSETTING_SUCCESS, orderSettings);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.GET_ORDERSETTING_FAIL);
        }
    }

    /**
     * 设置预约人数
     * @param orderSetting
     * @return
     */
    @PutMapping(path = "/updateOrderSettingNumber")
    public Result updateOrderSettingNumber(@RequestBody OrderSetting orderSetting) {
        try {
            orderSettingService.updateOrderSettingNumber(orderSetting);
            return new Result(true, MessageConstant.ORDERSETTING_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.ORDERSETTING_FAIL);

        }
    }

    @PostMapping("/findOrdersPage")
    public Result findOrdersPage(String value1,String  value2,String value3,String value4 ,@RequestBody QueryPageBean queryPageBean){

        try{
            String orderType=null;
            if ("1".equals(value2)){
                orderType="微信预约";
            }else if ("0".equals(value2)){
                orderType="电话预约";
            }

            String orderStatus=null;
            if ("1".equals(value3)){
                orderStatus="未到诊";
            }else if ("0".equals(value3)){
                orderStatus="已到诊";
            }

            PageResult pageResult= orderSettingService.queryOrderSetting( value1,  orderType, orderStatus, value4 , queryPageBean);

            return new Result(true,MessageConstant.GET_ORDERSETTING_LIST_SUCCESS,pageResult);

        }catch (Exception e){
            e.printStackTrace();
            return new Result(false,MessageConstant.GET_ORDERSETTING_LIST_FAIL);

        }
    }

    /**
     * 电话添加预约
     */

    @PostMapping("/submit")
    public Result submit(@RequestBody Map<String, String> map,Integer[] setmealIds){

        System.out.println("   map       "+map);

        try{
            //设置预约方式
            map.put("orderType", Order.ORDERTYPE_TELEPHONE);

            //提交预约数据
            Result result = orderService.order(map,setmealIds);

            if (result.isFlag()) {
                //发送短信提醒
                SMSUtils.sendShortMessage(SMSUtils.ORDER_NOTICE, map.get("telephone"), map.get("orderDate"));
            }

            return result;

        }catch (Exception e){
            e.printStackTrace();
            return new Result(false,MessageConstant.ORDER_FAIL);

        }
    }

    @GetMapping("/findById/{id}")
    public Result findById(@PathVariable Integer id){
        try{

            //提交预约数据
            Order order= orderService.findById(id);

            HashMap<String, Object> map = new HashMap<>();
            map.put("orderId",order.getId()+"");
            map.put("memberId",order.getMemberId()+"");
            map.put("orderDate",order.getOrderDate());
            map.put("orderType",order.getOrderType());
            map.put("orderStatus",order.getOrderStatus());
            map.put("setmealId",order.getSetmealId()+"");
            map.put("name",order.getMember().getName());
            map.put("sex",order.getMember().getSex());
            map.put("idCard",order.getMember().getIdCard());
            map.put("telephone",order.getMember().getPhoneNumber());
            map.put("birthday",order.getMember().getBirthday());
            map.put("age",order.getMember().getAge());
            map.put("marriyStatus",order.getMember().getMarriyStatus());
            return new Result(true,MessageConstant.QUERY_ORDER_SUCCESS,map);

        }catch (Exception e){
            e.printStackTrace();
            return new Result(false,MessageConstant.QUERY_ORDER_FAIL);

        }
    }


    /**
     * 电话编辑预约
     */

    @PostMapping("/updateOrder")
    public Result updateOrder(@RequestBody Map<String, String> map,Integer[] setmealIds){
        System.out.println("   map       "+map);
        try{
            //设置预约方式
            map.put("orderType", Order.ORDERTYPE_TELEPHONE);
            //提交预约数据
            Result result = orderService.update(map,setmealIds);
            if (result.isFlag()) {
                //发送短信提醒
                SMSUtils.sendShortMessage(SMSUtils.ORDER_NOTICE, map.get("telephone"), map.get("orderDate"));
            }
            return result;

        }catch (Exception e){
            e.printStackTrace();
            return new Result(false,MessageConstant.ORDER_FAIL);

        }
    }
    @PostMapping("/deleteOrderById")
    public Result deleteOrderById(Integer id,String orderDate){

        try{

            orderService.delete(id,orderDate);

            return new Result(true,MessageConstant.DELETE_ORDER_SUCCESS);

        }catch (Exception e){
            e.printStackTrace();
            return new Result(false,MessageConstant.DELETE_ORDER_FAIL);

        }
    }

    //修改订单为已到诊
    @PostMapping("/updateOrderStatus")
    public Result updateOrderStatus(Integer id){

        try{

            orderService.updateOrderStatusById(id);

            return new Result(true,MessageConstant.DET_ORDER_STATUS_SUCCESS);

        }catch (Exception e){
            e.printStackTrace();
            return new Result(false,MessageConstant.DET_ORDER_STATUS_FALL);
        }

    }
}
